package cn.zhiwen.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: wuzhiwen
 * @Date: 2018/10/22 16:44
 * @Description:
 */
@Configuration
public class MvcMessageConverter {

    @Bean
    public HttpMessageConverters httpMessageConverters() {
        //定义一个转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //添加fastjson的配置信息 比如 ：是否要格式化返回的json数据

//        QuoteFieldNames----------输出key时是否使用双引号,默认为true
//        WriteMapNullValue--------是否输出值为null的字段,默认为false
//        WriteNullNumberAsZero----数值字段如果为null,输出为0,而非null
//        WriteNullListAsEmpty-----List字段如果为null,输出为[],而非null
//        WriteNullStringAsEmpty---字符类型字段如果为null,输出为"",而非null
//        WriteNullBooleanAsFalse--Boolean字段如果为null,输出为false,而非null
//        WriteDateUseDateFormat---Date的日期转换器
        //WriteNonStringKeyAsString
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.WriteNonStringKeyAsString);
        //在转换器中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        List<MediaType> mediaTypeList = new ArrayList<>();
        mediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(mediaTypeList);
        return new HttpMessageConverters(fastConverter);
    }

}
